package com.itxiuyixiu.homework.security.config;

import com.itxiuyixiu.homework.entity.enums.RoleType;
import com.itxiuyixiu.homework.security.handler.ApiAuthenticationFailureHandler;
import com.itxiuyixiu.homework.security.service.StudentDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * @author 黄磊
 * @date 2020/3/6
 */
@Order(2)
@Configuration
public class StudentSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private StudentDetailsServiceImpl studentDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(studentDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.antMatcher("/student/**")
                .formLogin()
                .loginPage("/student/login.html")
                .loginProcessingUrl("/student/login")
                .defaultSuccessUrl("/student/application1.html", true)
                .failureHandler(new ApiAuthenticationFailureHandler())
                .permitAll()
                .and()
                .logout()
                .logoutUrl("/student/logout")
                .logoutSuccessUrl("/student/login.html")
                .and()
                .authorizeRequests()
                .anyRequest().hasAuthority(RoleType.STUDENT)
                .and().csrf().disable();
    }
}
